package com.distribute.core.notify.redis.redisTemplate;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.distribute.common.Constants;
import com.distribute.core.core.BaseNotifyMessage;
import com.distribute.core.notify.DLCNotify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 发布更新方式 实现
 *
 * @author chennengcheng
 * @date 2021-09-15 10:43
 * @remark
 */
public class RedisTemplateTopicNotifyImpl implements DLCNotify {

    private static final Logger log = LoggerFactory.getLogger(RedisTemplateTopicNotifyImpl.class);

    private RedisTemplate redisTemplate;

    public RedisTemplateTopicNotifyImpl(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void notifyCacheUpdate(String modelPrefix, String model, String data) {
        try {
            BaseNotifyMessage redisBaseNotifyMessage = BaseNotifyMessage.buildNotifyPart(data);
            redisBaseNotifyMessage.setModelPrefix(modelPrefix);
            redisBaseNotifyMessage.setModel(model);
            String topicId = Constants.DLC_CACHE + StrUtil.COLON + modelPrefix + StrUtil.COLON + model;
            redisTemplate.convertAndSend(topicId, JSONUtil.toJsonStr(redisBaseNotifyMessage));
        }catch (Exception e) {
            log.error("本地缓存通知失败：" + JSONUtil.toJsonStr(e));
        }
    }

    @Override
    public void notifyCacheUpdateAll(String modelPrefix, String model) {
        try {
            BaseNotifyMessage notifyMessage = BaseNotifyMessage.buildNotifyAll();
            notifyMessage.setModelPrefix(modelPrefix);
            notifyMessage.setModel(model);
            String topicId = Constants.DLC_CACHE + StrUtil.COLON + modelPrefix + StrUtil.COLON + model;
            redisTemplate.convertAndSend(topicId, JSONUtil.toJsonStr(notifyMessage));
        }catch (Exception e) {
            log.error("本地缓存通知失败：" + JSONUtil.toJsonStr(e));
        }
    }
}
